<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="/static/css/base.css">
</head>

<body>
  <h2>我是home页</h2>
  <button id="add">增加一个学生</button>
  <ul>
    <% if(!stus.length) {%>
      <li>暂无学生</li>
    <%}%>
    <% for(var i=0; i<stus.length; i++) { %>
      <li>
        <h3>学生姓名：<%= stus[i].name %>
        </h3>
        <p>学生年龄：<%= stus[i].age %>
        </p>
        <p>学生性别：<%= stus[i].gender?'女':'男' %>
        </p>
        <button data-id="<%= stus[i]._id %>" class="update">点击修改学生信息</button>
        <button data-id="<%= stus[i]._id %>" class="del">
          删除
        </button>
      </li>
      <% } %>
  </ul>
  <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
  <script>
    $(function () {
      $("#add").click(function () {
        $.ajax({
          url: '/addStu',
          type: 'post',
          data: {
            name: '学生n',
            age: 18,
            gender: 1
          },
          success: function (res) {
            console.log(res);
            if (res.code === 0) {
              alert(res.msg);
              // 刷新页面
              history.go(0)
            }
          }
        })
      })
      // 修改
      $('.update').click(function () {
        $.ajax({
          url: '/updateStu',
          type: 'post',
          data: {
            _id: this.dataset.id,
            age: 100
          },
          success: function (res) {
            if (res.code === 0) {
              alert(res.msg);
              history.go(0);
            }
          }
        })
      })
      // 删除
      $('.del').click(function () {
        if (confirm('您确认删除嘛')) {
          $.ajax({
            url: '/del',
            data: {
              id: this.dataset.id
            },
            success: function (res) {
              if (res.code === 0) {
                alert(res.msg);
                history.go(0)
              }
            }
          })
        }
      })
    })
  </script>
</body>

</html>